"""This module provides zhuhu small"""

import datetime
import json
import os
import platform
import time

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from playwright.sync_api import Page, sync_playwright


########################################################################
class CMyZhishi:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """

    def __init__(
        self,
        cookies_path: str,
        login_url: str,
        upload_picture_url: str,
        upload_mp4_url: str,
    ):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        # 想法 ---喜欢
        self.user_list = None
        self.context = None
        print("create CMyWeiBo")

    def __del__(self):
        print("CMyWeiBo is being destroyed")

    def upload_picture(
        self, picture_path_list: str, habit_name: str, habit_detail: str
    ):
        """
        upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
                self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(
                    channel="chrome", headless=display_headless
                )
            login_page = self.login_or_restore_cookies()
            print("login_or_restore_cookies")
            self.msg_up_load(login_page, picture_path_list, habit_name, habit_detail)
            self.browser.close()

    def login_or_restore_cookies(self) -> Page:
        """
        登录
        """
        # https://useragent.buyaocha.com/
        #  https://http.dev/user-agent
        userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
        elif sys == "Darwin":
            # chrome://version/
            userAgent = "ozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"

        self.context = self.browser.new_context(user_agent=userAgent)
        self.context.clear_cookies()
        page = self.context.new_page()
        page.goto(self.login_url)
        if os.path.exists(self.cookies_path):
            with open(self.cookies_path, "r", encoding="utf-8") as f:
                cookies = json.load(f)
            self.context.add_cookies(cookies)
            time.sleep(3)
            page.goto(self.login_url)
            time.sleep(3)

        if os.path.exists(self.cookies_path):
            pass
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(30)
            cookies = page.context.cookies()
            with open(self.cookies_path, "w", encoding="utf-8") as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page

    def do_auto_task(self, page: Page, habit_name: str):
        """ """
        #
        page.goto(self.upload_picture_url)
        page.wait_for_timeout(5000)
        print(f"open  {self.upload_picture_url}")
        page.mouse.down()
        page.mouse.down()

        if self.upload_picture_url == "https://wx.zsxq.com/group/15552545485212":
            page.get_by_text("最新", exact=True).click()
            page.wait_for_timeout(1000)

        # first click
        page.locator(".like").first.click()
        page.wait_for_timeout(8000)
        page.mouse.down()
        page.mouse.down()
        # css
        page.locator(".comment").first.click()
        # https://www.runoob.com/css/css-combinators.html
        page.locator("quill-editor div").nth(1).fill("👍")
        page.get_by_text("评论", exact=True).click()

        # second click
        page.locator(
            "app-topic:nth-child(8) > .topic-container > div > div:nth-child(3) > .operation-icon-container > .operation-icon > .like"
        ).click()
        page.wait_for_timeout(8000)


###############################################################


def interface_auo_zhishi_top(habit_name: str, url: str):
    """
    对外调用接口
    """
    print("interface_auo_upload_zhihu_small")
    sys = platform.system()
    login_url = "https://wx.zsxq.com/login"
    shenjian_url = url
    upload_mp4_url = "https://wx.zsxq.com/group/554588421184"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\zhishi_big.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/zhishi_big.json"
    else:
        cookies_path = r"/root/bin/zhishi_big.json"
    autoupload = CMyZhishi(cookies_path, login_url, shenjian_url, upload_mp4_url)

    # create an instance
    with sync_playwright() as playwright:
        display_headless = False
        sys = platform.system()
        if sys == "Linux":
            display_headless = True  # no windows
            browser = playwright.chromium.launch(headless=display_headless)
        else:
            browser = playwright.chromium.launch(
                channel="chrome", headless=display_headless
            )
        autoupload.browser = browser
        login_page = autoupload.login_or_restore_cookies()
        #  do task
        try:
            autoupload.do_auto_task(login_page, habit_name)
            autoupload.browser.close()
        except Exception as err:
            print(f"Unexpected {err=}, {type(err)=}")
            autoupload.browser.close()


###################################################
def auto_zhishi_top():
    """
    日更 50字
    """
    habit_name = "21点远离手机提醒"

    try:
        interface_auo_zhishi_top(habit_name, "https://wx.zsxq.com/group/554588421184")
        interface_auo_zhishi_top(habit_name, "https://wx.zsxq.com/group/15552545485212")
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")


if __name__ == "__main__":
    auto_zhishi_top()
    job_defaults = {"coalesce": False, "max_instances": 1}
    # 调度器组件
    backsched = BlockingScheduler(job_defaults=job_defaults, timezone="Asia/Shanghai")
    backsched.add_job(
        auto_zhishi_top, CronTrigger.from_crontab("0 18 * * *"), id="get_up"
    )
    backsched.start()
    # playwright codegen https://wx.zsxq.com/group/554588421184
    # playwright codegen https://wx.zsxq.com/group/51128814218244
